﻿using ModuleBase.googoltech.GTS;
using ModuleBase;
using Newtonsoft.Json;
using Prism.Ioc;
using System.Diagnostics;
using HalconDotNet;
using GeneralMotionControlProject.Vision.Models;
using GeneralMotionControlProject.Common.Services;

namespace FlyGrabAction
{
    public class FlyGrabAction : ModuleBase.ModuleBase
    {
        private IAxisCardService _axisCardService;
        private ModuleStateService _moduleStateService;
        bool outputs = false;
        private IContainerProvider _containerProvider;
        private IHIKCameraService camera;
        Stopwatch sw = new Stopwatch();
        private readonly MVisionFunctions mVisionFunctions;
        private MPoint InitPoint;
        AxisParm _axis;
        bool isGrabing = false;
        CancellationTokenSource source0;
        int calcToken = 0;
        HTuple calibHomMat2D1, calibHomMat2D2;
        private MRec mRec = new MRec();

        private int _parameter1 = 0;
        public int Parameter1
        {
            get => _parameter1;
            set
            {
                if (_parameter1 != value)
                {
                    _parameter1 = value;
                    OnPropertyChanged(nameof(Parameter1));
                }
            }
        }
        private int _parameter2 = 1;
        public int Parameter2
        {
            get => _parameter2;
            set
            {
                if (_parameter2 != value)
                {
                    _parameter2 = value;
                    OnPropertyChanged(nameof(Parameter2));
                }
            }
        }
        private double _parameter3 = 20;
        public double Parameter3
        {
            get => _parameter3;
            set
            {
                if (_parameter3 != value)
                {
                    _parameter3 = value;
                    OnPropertyChanged(nameof(Parameter3));
                }
            }
        }
        private string _parameter4;
        public string Parameter4
        {
            get => _parameter4;
            set
            {
                if (_parameter4 != value)
                {
                    _parameter4 = value;
                    OnPropertyChanged(nameof(Parameter4));
                }
            }
        }
        private double _parameter5 = 0;
        public double Parameter5
        {
            get => _parameter5;
            set
            {
                if (_parameter5 != value)
                {
                    _parameter5 = value;
                    OnPropertyChanged(nameof(Parameter5));
                }
            }
        }
        //private string _parameter6;
        //public string Parameter6
        //{
        //    get => _parameter6;
        //    set
        //    {
        //        if (_parameter6 != value)
        //        {
        //            _parameter6 = value;
        //            OnPropertyChanged(nameof(Parameter6));
        //        }
        //    }
        //}
        private double _parameter7 = 0;
        public double Parameter7
        {
            get => _parameter7;
            set
            {
                if (_parameter7 != value)
                {
                    _parameter7 = value;
                    OnPropertyChanged(nameof(Parameter7));
                }
            }
        }
        private double _parameter8 = 100;
        public double Parameter8
        {
            get => _parameter8;
            set
            {
                if (_parameter8 != value)
                {
                    _parameter8 = value;
                    OnPropertyChanged(nameof(Parameter8));
                }
            }
        }
        private string _parameter9;
        public string Parameter9
        {
            get => _parameter9;
            set
            {
                if (_parameter9 != value)
                {
                    _parameter9 = value;
                    OnPropertyChanged(nameof(Parameter9));
                }
            }
        }
        private string _parameter10 = "Top_A8";
        public string Parameter10
        {
            get => _parameter10;
            set
            {
                if (_parameter10 != value)
                {
                    _parameter10 = value;
                    OnPropertyChanged(nameof(Parameter10));
                }
            }
        }
        public override Dictionary<string, object> GetProperties()
        {
            return new Dictionary<string, object>
            {
                { "Hand", Parameter1 },
                { "相机", Parameter9 },
                { "轴号", Parameter2 },
                { "速度", Parameter3 },
                { "校准文件地址", Parameter4 },
                { "飞拍延时", Parameter5 },
                //{ "图片地址", Parameter6 },
                { "允许偏差值", Parameter7 },
                { "相机曝光时间", Parameter8 },
                { "轴卡参数名", Parameter10 },
            };
        }

        public override Dictionary<string, List<object>> PropertyOptions { get; } = new Dictionary<string, List<object>>
        {
            { "Hand", new List<object>{ 0,1 } },
            { "轴号", new List<object>{ 1,2,3,4,5,6,7,8 } },
            { "相机" ,new List<object>{ "Camera1", "Camera2", "Camera3", "Camera4" } },
        };

        public FlyGrabAction(IContainerProvider containerProvider, ModuleStateService moduleStateService)
        {
            _moduleStateService = moduleStateService;
            _containerProvider = containerProvider;
            Name = "飞拍：膜";
            var id = this.Id;
            DisplayNameToPropertyNameMap = new Dictionary<string, string>
            {
                { "Hand", nameof(Parameter1) },
                { "相机",  nameof(Parameter9) },
                { "轴号",  nameof(Parameter2) },
                { "速度",  nameof(Parameter3) },
                { "校准文件地址",  nameof(Parameter4) },
                { "飞拍延时",  nameof(Parameter5) },
                //{ "图片地址",  nameof(Parameter6) },
                { "允许偏差值",  nameof(Parameter7) },
                { "相机曝光时间",  nameof(Parameter8)},
                { "轴卡参数名",  nameof(Parameter10)},
            };
        }

        public override bool Execute()
        {
            camera = _containerProvider.Resolve<IHIKCameraService>(Parameter9);
            _axisCardService = _containerProvider.Resolve<IAxisCardService>(Parameter10);
            Status = ModuleStatus.Executing; // 设置状态为执行中
            _axis = GetAxisByNumber((int)Parameter2);
            HTuple offsetX = new HTuple(0);
            HTuple offsetY = new HTuple(0);
            using var mdb = _containerProvider.Resolve<MDbContext>();
            string CurPartNum = "Test";
            bool imageCalcFinishFlag = false;
            VisionResult vresult = new VisionResult();
            isGrabing = false;

            var _mParam = mdb.MParams.FirstOrDefault(x => x.Name == "CurPartNum");
            if (_mParam != null)
            {
                CurPartNum = _mParam.Value;
            }
            try
            {
                HOperatorSet.ReadTuple(System.IO.Path.Combine(System.Environment.CurrentDirectory, Parameter4, "CalibHomMat2D.tup"), out calibHomMat2D1);
                int stepNum = 0;
                while (true)
                {
                    switch (stepNum)
                    {
                        // 飞拍
                        case 0:
                            if (!_moduleStateService.IsStopped)
                            {
                                source0 = new CancellationTokenSource();
                                CancellationToken token = source0.Token;
                                isGrabing = true;
                                MyFunc.AddMessage($"轴 {Parameter2} 开始飞拍");
                                Task.Run(() => GrabAction(token), token).ContinueWith(art => { isGrabing = false; });
                                stepNum = 1;
                            }
                            break;
                        case 1:
                            if (!_moduleStateService.IsStopped && !isGrabing)
                                if (!isGrabing)
                                {
                                    #region 存图
                                    Task.Run(() =>
                                    {
                                        string dirpath = Path.Combine(System.Environment.CurrentDirectory, "CameraPhotos", CurPartNum, DateTime.Now.ToString("yyyyMMddHHmmss"), Parameter1.ToString());
                                        try
                                        {
                                            Directory.CreateDirectory(dirpath);
                                            foreach (var item in _axisCardService.ImageList)
                                            {
                                                try
                                                {
                                                    HOperatorSet.WriteImage(item.MImage, "jpeg", 0, Path.Combine(dirpath, $"{DateTime.Now:yyyyMMddHHmmss}_{item.Kind}_{item.CameraHand}_{item.Track}_{item.ImagePcsOrder}.jpg"));
                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                        }
                                    });
                                    #endregion
                                    #region 计算图1
                                    imageCalcFinishFlag = false;
                                    Task.Run(() =>
                                    {
                                        var _points = mdb.XYZPoints.Where(p => p.Hand == Parameter1 && p.IsUse).OrderBy(p => p.PcsOrder);

                                        if (_points.Any())
                                        {
                                            _points.ToList().ForEach(p =>
                                            {
                                                var visionPcs = mdb.VisionPoints.FirstOrDefault(v => v.Hand == 0 && v.PcsOrder == p.PcsOrder);
                                                if (visionPcs != null)
                                                {
                                                    HOperatorSet.GenRectangle1(out var rec01, visionPcs.Rec1Row1, visionPcs.Rec1Column1, visionPcs.Rec1Row2, visionPcs.Rec1Column2);

                                                    var flyimage = _axisCardService.ImageList.FirstOrDefault(img => img.CameraHand == visionPcs.CameraHand && img.Kind == visionPcs.ImageKind && img.Track == visionPcs.Track && img.ImagePcsOrder == visionPcs.ImagePcsOrder);
                                                    if (flyimage != null)
                                                    {
                                                        //0:未做模板 1:没找到 2:超限 200:PASS
                                                        vresult.PcsOrder = p.PcsOrder;
                                                        vresult.r_name = p.Name;
                                                        vresult.r_recScale = rec01;
                                                        while (calcToken % 2 != 0 && calcToken < 999)
                                                        {
                                                            System.Threading.Thread.Sleep(100);
                                                        }
                                                        calcToken++;
                                                        try
                                                        {
                                                            HOperatorSet.CopyObj(flyimage.MImage, out var imaga1, 1, -1);
                                                            vresult.r_image = imaga1;

                                                            var scripts = mdb.VisionScripts.Where(script => script.PointId == p.Id && script.IsUse).OrderBy(script => script.PcsOrder);
                                                            if (scripts.Any())
                                                            {
                                                                var list = scripts.ToList();
                                                                foreach (var script in list)
                                                                {
                                                                    MFunc.VisionAction(mdb, mVisionFunctions, script.ScriptFileName, imaga1, out var r_row, out var r_column, out var r_angle, out var result, out var r_region, out var additionalMessage);

                                                                    vresult.r_additional_msg = additionalMessage;
                                                                    bool rflag = result.I == 1 && r_row.TupleLength() > 0 && r_column.TupleLength() > 0 && r_angle.TupleLength() > 0;
                                                                    if (rflag)
                                                                    {
                                                                        HTuple _calc_qx, _calc_qy;
                                                                        if (visionPcs.CameraHand == Parameter1)
                                                                        {
                                                                            HOperatorSet.AffineTransPoint2d(calibHomMat2D1, r_row, r_column, out _calc_qx, out _calc_qy);
                                                                        }
                                                                        else
                                                                        {
                                                                            HOperatorSet.AffineTransPoint2d(calibHomMat2D2, r_row, r_column, out _calc_qx, out _calc_qy);
                                                                        }
                                                                        var CameraCalib = mdb.MParams.FirstOrDefault(param => param.Hand == Parameter1 && param.Name == "CameraCalib");
                                                                        var calibPoint = JsonConvert.DeserializeObject<MPoint>(CameraCalib.Value);
                                                                        var flypoint = mdb.FlyGrabPoints.FirstOrDefault(fly => fly.Hand == visionPcs.CameraHand && fly.Kind == visionPcs.ImageKind && fly.Track == visionPcs.Track && fly.PcsOrder == visionPcs.ImagePcsOrder);
                                                                        if (flypoint != null)
                                                                        {
                                                                            var calc_qx = _calc_qx + flypoint.X - calibPoint.X;
                                                                            var calc_qy = _calc_qy + flypoint.Y - calibPoint.Y;
                                                                            double deltaX = (p.X - calc_qx.D) * -1;
                                                                            double deltaY = (p.Y - calc_qy.D) * -1;
                                                                            double deltaAngle = ((visionPcs.ST_Angle - r_angle) * -1).TupleDeg().D;



                                                                            HOperatorSet.TestRegionPoint(rec01, r_row - mRec.Height / 2, r_column - mRec.Width / 2, out var isInside1);
                                                                            HOperatorSet.TestRegionPoint(rec01, r_row + mRec.Height / 2, r_column + mRec.Width / 2, out var isInside2);

                                                                            if (Math.Abs(deltaX) > Parameter7 || Math.Abs(deltaY) > Parameter7 || (isInside1.I == 0 || isInside2.I == 0))
                                                                            {
                                                                                vresult.result = VResult.Limit;
                                                                                if (string.IsNullOrEmpty(vresult.r_additional_msg))
                                                                                {
                                                                                    vresult.r_additional_msg = "Limit";
                                                                                }
                                                                                else
                                                                                {
                                                                                    vresult.r_additional_msg += ";Limit";
                                                                                }
                                                                                r_region.Dispose();
                                                                                outputs = false;
                                                                            }
                                                                            else
                                                                            {
                                                                                vresult.r_row = r_row;
                                                                                vresult.r_column = r_column;
                                                                                vresult.r_region = r_region;

                                                                                vresult.result = VResult.PASS;
                                                                                vresult.deltaX = deltaX;
                                                                                vresult.deltaY = deltaY;
                                                                                vresult.deltaAngle = deltaAngle;
                                                                                outputs = true;
                                                                                break;
                                                                            }

                                                                        }
                                                                        else
                                                                        {
                                                                            vresult.result = VResult.NG;
                                                                            outputs = false;
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        vresult.result = VResult.NG;
                                                                        outputs = false;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                vresult.result = VResult.NG;
                                                                outputs = false;
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            vresult.result = VResult.NG;
                                                            outputs = false;
                                                        }
                                                    }
                                                }
                                            });

                                        }
                                    }).ContinueWith(arg => { imageCalcFinishFlag = true; });
                                    #endregion

                                    stepNum = 2;
                                }
                            break;
                        case 2:
                            if (!_moduleStateService.IsStopped && imageCalcFinishFlag)
                            {
                                if (vresult.result == VResult.PASS)
                                {
                                    _mParam = mdb.MParams.FirstOrDefault(p => p.Name == "MoldDeltaXYR" && p.Hand == Parameter1);
                                    if (_mParam != null)
                                    {
                                        MPoint mPoint = JsonConvert.DeserializeObject<MPoint>(_mParam.Value);
                                        mPoint.X = vresult.deltaX;
                                        mPoint.Y = vresult.deltaY;
                                        mPoint.R = vresult.deltaAngle;
                                    }
                                    else
                                    {
                                        MPoint mPoint = new MPoint()
                                        {
                                            X = vresult.deltaX,
                                            Y = vresult.deltaY,
                                            Z = 0,
                                            R = vresult.deltaAngle
                                        };
                                        mdb.MParams.Add(new MParam()
                                        {
                                            Name = "MoldDeltaXYR",
                                            Value = JsonConvert.SerializeObject(mPoint),
                                            Type = typeof(string).Name,
                                            Hand = Parameter1
                                        });
                                    }
                                    mdb.SaveChanges();
                                    outputs = true;
                                }
                                else
                                {
                                    outputs = false;
                                }
                                stepNum = 3;
                            }
                            break;
                        case 3:
                            return outputs;
                    }
                }
            }
            catch (Exception exp)
            {
                outputs = false;
            }
            return outputs;
        }

        public override async Task<bool> ExecuteAsync()
        {
            var result = await Task.Run(() => Execute());
            return result;
        }

        public override void Initialize()
        {

        }
        private AxisParm GetAxisByNumber(int axisNumber)
        {
            switch (axisNumber)
            {
                case 1: return _axisCardService.A1;
                case 2: return _axisCardService.A2;
                case 3: return _axisCardService.A3;
                case 4: return _axisCardService.A4;
                case 5: return _axisCardService.A5;
                case 6: return _axisCardService.A6;
                case 7: return _axisCardService.A7;
                case 8: return _axisCardService.A8;
                default: return _axisCardService.A1;
            }
        }
        /// <summary>
        /// 飞拍
        /// </summary>
        /// <param name="token"></param>
        private void GrabAction(CancellationToken token)
        {
            #region 变量
            int stepnum = 500;
            Queue<FlyGrabPoint> GrabPointQueue = new Queue<FlyGrabPoint>();
            FlyGrabPoint GrabPoint = new FlyGrabPoint();
            Stopwatch sw = new Stopwatch();
            bool GrabDone = false;
            bool GrabResutl = false;
            bool FlyFinish = false;
            FlyGrabPoint[] PathFlyGrabPoint = new FlyGrabPoint[0];
            int[] Buf1 = new int[0], Buf2 = new int[0];
            int ImageCount = 0;
            int trackCount = 0;
            bool imageFailDone = false;
            using var mdb = _containerProvider.Resolve<MDbContext>();
            #endregion
            _axisCardService.ImageList.Clear();
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                try
                {
                    switch (stepnum)
                    {
                        #region 单拍
                        case 500:
                            if (!_moduleStateService.IsStopped)
                            {
                                GrabPointQueue.Clear();
                                var grabpoints = mdb.FlyGrabPoints.Where(f => f.Hand == Parameter1 && f.Kind == 0).OrderBy(f => f.PcsOrder);
                                if (grabpoints.Any())
                                {
                                    grabpoints.ToList().ForEach(p =>
                                    {
                                        GrabPointQueue.Enqueue(p);
                                    });
                                }
                                stepnum = 501;
                            }
                            break;
                        case 501:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (GrabPointQueue.TryPeek(out var p))
                                {
                                    if (GrabPointQueue.TryPeek(out p))
                                    {
                                        GrabPoint = GrabPointQueue.Dequeue();
                                    }
                                    else
                                    {
                                        GrabPoint = new FlyGrabPoint
                                        {
                                            Id = -1,
                                            X = InitPoint.X,
                                            Y = InitPoint.Y,
                                            Z = InitPoint.Z,
                                            UseLight1 = true,
                                            UseLight2 = true
                                        };
                                    }
                                    stepnum = 502;
                                }
                                else
                                {
                                    stepnum = 600;
                                }
                            }
                            break;
                        case 502:
                            if (!_moduleStateService.IsStopped)
                            {
                                GTSCard.AxisPosMove(ref _axis, GrabPoint.Y, Parameter3);
                                stepnum = 503;
                            }
                            break;
                        case 503:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (GTSCard.AxisPosMoveCheckDone(_axis))
                                {
                                    sw.Restart();
                                    stepnum = 504;
                                }
                            }
                            else
                            {
                                GTSCard.AxisStop(_axis, 0);
                                stepnum = 502;
                            }
                            break;
                        case 504:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (sw.Elapsed.TotalSeconds > Parameter5)
                                {
                                    stepnum = 505;
                                }
                            }
                            break;
                        case 505:
                            if (!_moduleStateService.IsStopped)
                            {
                                GrabResutl = true;
                                if (GrabPoint.Id > 0)
                                {
                                    GrabDone = false;
                                    camera.ImageQueue?.Clear();
                                    camera.SetTriggerMode(0);
                                    camera.SetExposureTime((float)Parameter8);
                                    camera.StartGrabe();
                                    Task.Run(async () =>
                                    {
                                        bool breakFlag = false;
                                        Task task = new Task(() =>
                                        {
                                            int mIndex = 0;
                                            while (mIndex < 1 && !breakFlag)
                                            {
                                                HObject? hObj;
                                                if (camera.ImageQueue.TryPeek(out hObj))
                                                {
                                                    camera.ImageQueue.TryDequeue(out hObj);
                                                    _axisCardService.ImageList.Add(new FlyImage
                                                    {
                                                        CameraHand = 0,
                                                        MImage = hObj,
                                                        Track = 0,
                                                        ImagePcsOrder = GrabPoint.PcsOrder,
                                                        Kind = GrabPoint.Kind
                                                    });
                                                    mIndex++;
                                                }
                                            }
                                        });
                                        task.Start();
                                        var delay = Task.Delay(3000);
                                        if (await Task.WhenAny(task, delay) == delay)
                                        {
                                            GrabResutl = false;
                                            breakFlag = true;
                                        }
                                        camera.StopGrabe();

                                    }).ContinueWith(t => { GrabDone = true; });
                                }
                                else
                                {
                                    GrabDone = true;
                                }
                                stepnum = 506;
                            }
                            break;
                        case 506:
                            if (GrabDone)
                            {
                                GrabDone = false;
                                if (!GrabResutl)
                                {
                                    string alarmstr = string.Empty;
                                    if (!GrabResutl)
                                    {
                                        alarmstr += "相机拍照失败";
                                        MyFunc.AddMessage(alarmstr);
                                    }
                                    imageFailDone = false;
                                    stepnum = 507;
                                }
                                else
                                {
                                    stepnum = 501;
                                }
                            }
                            break;
                        case 507:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (imageFailDone)
                                {
                                    imageFailDone = false;
                                    stepnum = 505;
                                }
                            }
                            break;
                        #endregion
                        #region 飞拍
                        case 600:
                            if (!_moduleStateService.IsStopped)
                            {
                                FlyFinish = false;

                                var pathFlyPoints = mdb.FlyGrabPoints.Where(f => f.Hand == Parameter1 && f.Kind == 2 && f.Track == trackCount).OrderBy(f => f.PcsOrder);
                                if (pathFlyPoints.Any())
                                {
                                    PathFlyGrabPoint = pathFlyPoints.ToArray();
                                    var flyPoints = mdb.FlyGrabPoints.Where(f => f.Hand == Parameter1 && f.Kind == 1 && f.Track == trackCount).OrderBy(f => f.PcsOrder);
                                    if (flyPoints.Any())
                                    {
                                        var pointArr = flyPoints.ToArray();
                                        ImageCount = pointArr.Length;
                                        Buf1 = new int[pointArr.Length];
                                        double cameraGrabMovSpace = pointArr[0].Y > pointArr[pointArr.Length - 1].Y ? Parameter5 / 1000 * Parameter3 : Parameter5 / 1000 * Parameter3 * -1;
                                        for (int i = 0; i < pointArr.Length; i++)
                                        {
                                            Buf1[i] = (int)((pointArr[i].Y - PathFlyGrabPoint[0].Y + cameraGrabMovSpace) / _axis.Equiv);
                                        }
                                    }
                                    else
                                    {
                                        ImageCount = 0;
                                    }

                                    MyFunc.AddMessage($"相机 {Parameter9} ImageCount ：{ImageCount}");
                                }
                                else
                                {
                                    FlyFinish = true;
                                }
                                if (FlyFinish)
                                {
                                    MyFunc.AddMessage($"相机 {Parameter9} 飞拍完成");
                                    return;//飞拍完成
                                }
                                else
                                {
                                    stepnum = 601;
                                }
                            }
                            break;


                        case 601:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (!FlyFinish)
                                {
                                    GTSCard.AxisPosMove(ref _axis, PathFlyGrabPoint[0].Y, Parameter3);
                                }
                                else
                                {
                                    GTSCard.AxisPosMove(ref _axis, InitPoint.Y, Parameter3);
                                }
                                stepnum = 602;
                            }
                            break;
                        case 602:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (GTSCard.AxisPosMoveCheckDone(_axis))
                                {
                                    sw.Restart();
                                    stepnum = 603;
                                }
                            }
                            else
                            {
                                GTSCard.AxisStop(_axis, 0);
                                stepnum = 601;
                            }
                            break;
                        case 603:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (sw.Elapsed.TotalSeconds > Parameter5)
                                {
                                    stepnum = 604;
                                }
                            }
                            break;
                        case 604:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (ImageCount > 0)
                                {
                                    MyFunc.AddMessage($"相机 {Parameter9} 设置飞拍数据");
                                    GTSCard.AxisCompareUse1(_axis.CardNo, _axis.AxisId, Buf1);//设置飞拍数据

                                    camera.ImageQueue?.Clear();
                                    camera.SetExposureTime((float)Parameter8);
                                    camera.SetTriggerMode(1);
                                    camera.StartGrabe();
                                }
                                stepnum = 605;
                            }
                            break;
                        case 605:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (!FlyFinish)
                                {
                                    MyFunc.AddMessage($"相机 {Parameter9} 执行飞拍运动");
                                    GTSCard.AxisPosMove(ref _axis, PathFlyGrabPoint[1].Y, Parameter3);
                                }
                                else
                                {
                                    GTSCard.AxisPosMove(ref _axis, InitPoint.Y, Parameter3);
                                }
                                stepnum = 606;
                            }
                            break;
                        case 606:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (GTSCard.AxisPosMoveCheckDone(_axis))
                                {
                                    MyFunc.AddMessage($"相机 {Parameter9} 飞拍轴运动完成,确认拍照数据");
                                    GrabResutl = true;
                                    int count = 0;
                                    if (ImageCount > 0)
                                    {
                                        int _index = 0;
                                        var flyPoints = mdb.FlyGrabPoints.Where(f => f.Hand == Parameter1 && f.Track == trackCount && f.Kind == 1).OrderBy(f => f.PcsOrder);
                                        var _arr = flyPoints.ToArray();
                                        camera.StopGrabe();
                                        count = camera.ImageQueue.Count;
                                        if (camera.ImageQueue.Count >= _arr.Length)
                                        {
                                            while (camera.ImageQueue.TryDequeue(out var _img))
                                            {
                                                //先查有没有拍过
                                                var _imgrecord = _axisCardService.ImageList.FirstOrDefault(img => img.CameraHand == Parameter1 && img.Kind == 1 && img.Track == trackCount && img.ImagePcsOrder == _arr[_index].PcsOrder);
                                                if (_imgrecord == null)
                                                {
                                                    _axisCardService.ImageList.Add(new FlyImage
                                                    {
                                                        CameraHand = 0,
                                                        MImage = _img,
                                                        Track = trackCount,
                                                        ImagePcsOrder = _arr[_index].PcsOrder,
                                                        Kind = 1
                                                    });
                                                }
                                                else
                                                {
                                                    //拍过→更新
                                                    _imgrecord.MImage.Dispose();
                                                    _imgrecord.MImage = _img;
                                                }
                                                _index++;
                                            }
                                        }
                                        else
                                        {
                                            //图片长度不对
                                            GrabResutl = false;
                                        }
                                    }
                                    if (GrabResutl)
                                    {
                                        trackCount++;
                                        stepnum = 600;
                                    }
                                    else
                                    {
                                        string alarmstr = string.Empty;
                                        if (!GrabResutl)
                                        {
                                            string str = $"相机拍照失败:应拍{ImageCount}张，实拍{count}张";
                                            alarmstr += str;
                                            MyFunc.AddMessage(alarmstr);
                                        }
                                        imageFailDone = false;
                                        stepnum = 607;
                                    }
                                }
                            }
                            else
                            {
                                GTSCard.AxisStop(_axis, 0);
                                stepnum = 605;
                            }
                            break;
                        case 607:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (imageFailDone)
                                {
                                    MyFunc.AddMessage($"相机 {Parameter9} 飞拍失败");
                                    imageFailDone = false;
                                    stepnum = 600;
                                }
                            }
                            break;
                        #endregion
                        default:
                            break;
                    }
                }
                catch (Exception exp) { MyFunc.AddMessage(exp.ToString()); return; }
                System.Threading.Thread.Sleep(10);
            }
        }

        public override string Description => "飞拍模块：用于在运动过程中同步触发相机拍照，适用于高速产线检测。";
    }
}
